#if defined (_DEBUG)
#pragma comment (lib, "DelGE-d.lib")
#pragma comment (lib, "squirrelD.lib")
#pragma comment (lib, "sqstdlibD.lib")
#pragma comment (lib, "sqplusD.lib")
#pragma comment (lib ,"sqdbglibD.lib")
#else
#pragma comment (lib, "DelGE.lib")
#pragma comment (lib, "squirrel.lib")
#pragma comment (lib, "sqstdlib.lib")
#pragma comment (lib, "sqplus.lib")
#pragma comment (lib ,"sqdbglib.lib")
#endif

#include <lib\squirrel\sqplus.h>

#include "delge_squirrelglobals.h"
#include "delge_squirrelfunctions.h"
#include "delge_squirrelgame.h"
#include "delge_squirrelscreen.h"

using namespace SqPlus;

void CompileErrorHandler(HSQUIRRELVM v,const SQChar *sDescription, const SQChar *sSource, SQInteger line, SQInteger column);
static SQInteger RuntimeError(HSQUIRRELVM v);

int main()
{
	SquirrelVM::Init();

	sq_setcompilererrorhandler(SquirrelVM::GetVMPtr(), CompileErrorHandler);
	sq_newclosure(SquirrelVM::GetVMPtr(), RuntimeError, 0);
	sq_seterrorhandler(SquirrelVM::GetVMPtr());

	s_RegisterFunctions(SquirrelVM::GetVMPtr());

	Globals::sCurrentScreen = "";
	Globals::pGame = new MyGame();
	Globals::pScreen = new MyScreen();

	Globals::pGame->AddScreen(0, Globals::pScreen);

	SquirrelObject main;
	
	main = SquirrelVM::CompileScript("scripts/game.nut");
	try
	{
		SquirrelVM::RunScript(main);
		main.Reset();
	}
	catch (SquirrelError& error)
	{
		cerr << error.desc << endl;
		return EXIT_FAILURE;
	}

	Globals::pGame->Run(0);

	SquirrelVM::Shutdown();

	delete Globals::pScreen;
	delete Globals::pGame;

	return 0;
}

void CompileErrorHandler(HSQUIRRELVM v,const SQChar *sDescription, const SQChar *sSource, SQInteger line, SQInteger column)
{
	cerr << "Compile Error" << endl;
	cerr << sDescription << endl;
	cerr << sSource << endl;
	cerr << line << endl;
	cerr << column << endl;
}

static SQInteger RuntimeError(HSQUIRRELVM v)
{
	const SQChar* sDescription = "Unknown";
	const SQChar* sFunctionName = "Unknown";
	const SQChar* sSource = "Unknown";
	SQInteger line = 0;
	SQInteger stackLevel = 1;
	SQStackInfos stackInfo;

	if(sq_gettop(v) >= 1) 
		sq_getstring(v, 2, &sDescription);

	//while(SQ_SUCCEEDED())
	//{
		sq_stackinfos(v, stackLevel, &stackInfo);
		if (stackInfo.funcname) sFunctionName = stackInfo.funcname;
		if (stackInfo.source) sSource = stackInfo.source;
		line = stackInfo.line;
		//stackLevel ++;
	//}

	cerr << "Runtime Error" << endl;
	cerr << sDescription << endl;
	cerr << sSource << endl;
	cerr << sFunctionName << endl;
	cerr << line << endl;
	
	return 0;
}